package com.atguigu.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.atguigu.constant.MessageConstant;
import com.atguigu.dao.MemberMapper;
import com.atguigu.dao.OrderMapper;

import com.atguigu.dao.OrdersettingMapper;
import com.atguigu.pojo.*;
import com.atguigu.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Service(interfaceClass = OrderService.class)
@Transactional
public class OrderServiceImpl implements OrderService {


    @Autowired
    private OrdersettingMapper ordersettingMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private MemberMapper memberMapper;


    /*
     1、检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行预约
     2、检查用户所选择的预约日期是否已经约满，如果已经约满则无法预约
     4、检查当前用户是否为会员，如果是会员则直接完成预约，如果不是会员则自动完成注册并进行预约
     3、检查用户是否重复预约（同一个用户在同一天预约了同一个套餐），如果是重复预约则无法完成再次预约
     5、预约成功，更新当日的已预约人数
     */
    @Override
    public int save(Map map) {
        String orderDate = map.get("orderDate").toString();
        OrdersettingExample ordersettingExample = new OrdersettingExample();
        OrdersettingExample.Criteria criteria = ordersettingExample.createCriteria();
        String telephone =(String) map.get("telephone");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Date date=null;
        //1、检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行预约
        try {
            date = sdf.parse(orderDate);
            criteria.andOrderdateEqualTo(date);
        } catch (ParseException e) {
            e.printStackTrace();
            throw new RuntimeException("日期转换异常");
        }
        List<Ordersetting> ordersettings = ordersettingMapper.selectByExample(ordersettingExample);
        if (ordersettings == null || ordersettings.size() == 0 ){
            throw new RuntimeException(MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        //2、检查用户所选择的预约日期是否已经约满，如果已经约满则无法预约
        Ordersetting ordersetting = ordersettings.get(0);
        Integer number = ordersetting.getNumber();
        Integer reservations = ordersetting.getReservations();
        if (reservations >= number){
            throw new RuntimeException(MessageConstant.ORDER_FULL);
        }
        //3、检查用户是否重复预约（同一个用户在同一天预约了同一个套餐），如果是重复预约则无法完成再次预约
        MemberExample example = new MemberExample();
        MemberExample.Criteria criteria2 = example.createCriteria();
        criteria2.andPhonenumberEqualTo(telephone);
        List<Member> members = memberMapper.selectByExample(example);
        Integer menberId=null;
        //如果本身不是会员 那么自动注册会员
        if (members == null || members.size() == 0){
            //拿到需要的前端数据 传参数
            String name = map.get("name").toString();
            String sex = map.get("sex").toString();
            String idCard = map.get("idCard").toString();
            Member member = new Member(name,sex,idCard,telephone,new Date());
            memberMapper.insert(member);
            menberId = member.getId();
        }else {
            Member member = members.get(0);
            menberId = member.getId();
        }
        //走到这里之后  肯定会有会员了 有menberId了



        OrderExample orderExample = new OrderExample();
        OrderExample.Criteria criteria1 = orderExample.createCriteria();
        //同一个用户
        criteria1.andMemberIdEqualTo(menberId);
        //同一个时间
        criteria1.andOrderdateEqualTo(date);
        String setmealId = map.get("setmealId").toString();
        criteria1.andSetmealIdEqualTo(Integer.parseInt(setmealId));
        long count = orderMapper.countByExample(orderExample);

        if (count > 0 ){
            throw new RuntimeException(MessageConstant.HAS_ORDERED);
        }
        //能预约 1.订单表保存数据 并返回主键值 2.同时修改预约设置表中的已预约人数加1
        Order order =new Order(menberId,date,MessageConstant.WEIXIN,MessageConstant.CHUYOU_FAIL,Integer.parseInt(setmealId));
        orderMapper.insert(order);
        ordersetting.setReservations(ordersetting.getReservations()+1);
        ordersettingMapper.updateByExampleSelective(ordersetting,ordersettingExample);
        return order.getId();

    }

    @Override
    public Map findById(Integer id) throws Exception {
        Map map = orderMapper.findById(id);
        Date orderDate = (Date)map.get("orderDate");
        map.put("orderDate",DateUtils.parseDate2String(orderDate));
        return map;
    }

    @Override
    public List<Map<String, Object>> getSetmealReport() {
        return orderMapper.getSetmealReport();
    }
}
